import { Component, OnInit } from '@angular/core';
import { Validators, FormBuilder, ValidationErrors, AbstractControl, FormGroup, FormControl } from '@angular/forms';
import { Router, NavigationExtras, ActivatedRoute } from '@angular/router';
import { AlertController } from '@ionic/angular';
import {TranslateService} from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { AuthTokenService } from '@services/auth-token.service';
import {CustomToastProviderService} from '@common-components/common-toast/custom-toast-provider.service';
@Component({
  selector: 'app-add-bank-account',
  templateUrl: './add-bank-account.page.html',
  styleUrls: ['./add-bank-account.page.scss'],
})
export class AddBankAccountPage implements OnInit {
  bankNames = [
    {
      name: 'CITI BANK',
      value: 1
    },
    {
      name: 'OCBC BANK',
      value: 2
    },
    {
      name: 'FAB BANK',
      value: 3
    }
  ];

  addBankForm!: FormGroup
  constructor(
    private fb: FormBuilder,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    public alertController: AlertController,
    private translate: TranslateService,
    public http: HttpClient,
    private authTokenService: AuthTokenService,
    private customToast:CustomToastProviderService,
    private defaultLanguageService:DefaultLanguageService
  ) {
    this.addBankForm = this.fb.group({
      bankAccount:new FormControl('',{
        validators: [Validators.required,Validators.pattern(/^[0-9]{16}$/),Validators.maxLength(16)],
        updateOn:'blur'
      }),
      bankName: new FormControl('',{
        validators: [Validators.required]
      }),
    });

  }

  get bankAccount(){
    return this.addBankForm.get('bankAccount');
  }

  get bankName(){
    return this.addBankForm.get('bankName');
  }

  invalidAlert() {
    const alert:any = this.alertController.create({
      cssClass: 'my-custom-class',
      header: '',
      subHeader: '',
      message: 'Bank account number is invalid.',
      buttons: [{
        text:'Cancel',
        handler:()=>{

        }
      }, {
        text:'Re-enter',
        handler:()=>{

        }
      }]
    }).then(
      (resolveed)=>{
        resolveed.present();
      }
    );

  }

  accountAlert() {
    const alert:any = this.alertController.create({
      cssClass: 'my-custom-class',
      header: '',
      subHeader: '',
      message: 'You can only bind my personal account . Please re-enter your bank account number.',
      buttons: [{
        text:'Cancel',
        handler:()=>{

        }
      }, {
        text:'Re-enter',
        handler:()=>{

        }
      }]
    }).then(
      (resolveed)=>{
        resolveed.present();
      }
    );

    // alert.present();
  }

  bankAccountValidator() {
    return async (control: AbstractControl): Promise<ValidationErrors | null> => {
      const value = control.value;
      // this.invalidAlert();
      if (!value) {
        //http request
        //this.invalidAlert();
        return {
          valid: false,
          required: true
        };
      }
    };
  }

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe(
      (card: any) => {
        console.info(card);
        if(card.cardNumber && card.bankName){
          this.addBankForm.setValue(
            {
              bankAccount: card.cardNumber || '',
              bankName: card.bankName || ''
            },
            {
              onlySelf: false,
              emitEvent: true
            });
        }
      }
    )
  }

  appuserid = this.authTokenService.getAppUserId();
  toNext(formData) {
    const url = '/scm/app/getBankAccount.do';  
    let bankAccount = this.addBankForm.value.bankAccount;
    let bankName = this.addBankForm.value.bankName;
    let request = {
      "appuserid":this.appuserid,
      "bankAccount":bankAccount,
      "bankName":bankName
    };    
    this.http.post(url,request).subscribe(
      (response:any)=>{
        let body = response.responseBody;
        if(body){
          let navigationExtras: NavigationExtras = {
            queryParams: body
          };
          this.router.navigate(['/tabs/myAccount/bank-account/add-bank-account/account-info'], navigationExtras);
        }else{
          this.customToast.show({
            icon:false,
            iconSuccess:false,
            message:'Bank account number does not exist in the system',
            duration:2000
          });
        }
      });
   
  }

}
